<template>
  <div class="payment-result-page">
    <div class="result-container">
      <!-- 支付成功 -->
      <div v-if="paymentStatus === 'success'" class="result-content success">
        <div class="result-icon">
          <el-icon class="success-icon"><CircleCheck /></el-icon>
        </div>
        <h2 class="result-title">{{ t('dashboard.vipCenter.paymentResult.success.title') }}</h2>
        <p class="result-message">{{ t('dashboard.vipCenter.paymentResult.success.message') }}</p>
        
        <div class="success-details">
          <div class="detail-item">
            <span class="label">{{ t('dashboard.vipCenter.paymentResult.success.orderNo') }}</span>
            <span class="value">{{ orderInfo?.orderNo }}</span>
          </div>
          <div class="detail-item">
            <span class="label">{{ t('dashboard.vipCenter.paymentResult.success.planType') }}</span>
            <span class="value">{{ getPlanTypeText(orderInfo?.planType) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">{{ t('dashboard.vipCenter.paymentResult.success.amount') }}</span>
            <span class="value amount">¥{{ orderInfo?.amount?.toFixed(2) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">{{ t('dashboard.vipCenter.paymentResult.success.activationTime') }}</span>
            <span class="value">{{ formatTime(orderInfo?.paidAt) }}</span>
          </div>
        </div>

        <div class="action-buttons">
          <el-button type="primary" @click="goToProfile">
            {{ t('dashboard.vipCenter.paymentResult.success.viewVipStatus') }}
          </el-button>
          <el-button @click="goToHome">
            {{ t('dashboard.vipCenter.paymentResult.success.backHome') }}
          </el-button>
        </div>
      </div>

      <!-- 支付失败 -->
      <div v-else-if="paymentStatus === 'failed'" class="result-content failed">
        <div class="result-icon">
          <el-icon class="failed-icon"><CircleClose /></el-icon>
        </div>
        <h2 class="result-title">{{ t('dashboard.vipCenter.paymentResult.failed.title') }}</h2>
        <p class="result-message">{{ errorMessage || t('dashboard.vipCenter.paymentResult.failed.defaultMessage') }}</p>
        
        <div class="action-buttons">
          <el-button type="primary" @click="retryPayment">
            {{ t('dashboard.vipCenter.paymentResult.failed.retryPayment') }}
          </el-button>
          <el-button @click="goToHome">
            {{ t('dashboard.vipCenter.paymentResult.failed.backHome') }}
          </el-button>
        </div>
      </div>

      <!-- 支付取消 -->
      <div v-else-if="paymentStatus === 'cancelled'" class="result-content cancelled">
        <div class="result-icon">
          <el-icon class="cancelled-icon"><Warning /></el-icon>
        </div>
        <h2 class="result-title">{{ t('dashboard.vipCenter.paymentResult.cancelled.title') }}</h2>
        <p class="result-message">{{ t('dashboard.vipCenter.paymentResult.cancelled.message') }}</p>
        
        <div class="action-buttons">
          <el-button type="primary" @click="retryPayment">
            {{ t('dashboard.vipCenter.paymentResult.cancelled.retryPayment') }}
          </el-button>
          <el-button @click="goToHome">
            {{ t('dashboard.vipCenter.paymentResult.cancelled.backHome') }}
          </el-button>
        </div>
      </div>

      <!-- 加载中 -->
      <div v-else class="result-content loading">
        <div class="result-icon">
          <el-icon class="loading-icon"><Loading /></el-icon>
        </div>
        <h2 class="result-title">{{ t('dashboard.vipCenter.paymentResult.loading.title') }}</h2>
        <p class="result-message">{{ t('dashboard.vipCenter.paymentResult.loading.message') }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { 
  CircleCheck, 
  CircleClose, 
  Warning, 
  Loading 
} from '@element-plus/icons-vue'
import { useVipStore } from '@/stores/vip'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const vipStore = useVipStore()

// 响应式数据
const paymentStatus = ref<'success' | 'failed' | 'cancelled' | 'loading'>('loading')
const orderInfo = ref<any>(null)
const errorMessage = ref<string>('')

// Helper function to get plan type text
const getPlanTypeText = (planType: string) => {
  return planType === 'MONTHLY_VIP' 
    ? t('dashboard.vipCenter.paymentResult.success.monthlyVip')
    : t('dashboard.vipCenter.paymentResult.success.yearlyVip')
}

onMounted(async () => {
  await checkPaymentResult()
})

const checkPaymentResult = async () => {
  try {
    const { orderNo, success, cancelled, message } = route.query
    
    if (cancelled === 'true') {
      paymentStatus.value = 'cancelled'
      return
    }
    
    if (!orderNo) {
      paymentStatus.value = 'failed'
      errorMessage.value = t('dashboard.vipCenter.paymentResult.errors.missingOrderInfo')
      return
    }

    // 查询订单状态
    const orders = await fetchOrderDetails(orderNo as string)
    const order = orders.find((o: any) => o.orderNo === orderNo)
    
    if (!order) {
      paymentStatus.value = 'failed'
      errorMessage.value = t('dashboard.vipCenter.paymentResult.errors.orderNotFound')
      return
    }

    orderInfo.value = order
    
    if (order.status === 'PAID' || success === 'true') {
      paymentStatus.value = 'success'
      // 刷新VIP状态
      await vipStore.init()
      ElMessage.success(t('dashboard.vipCenter.paymentResult.messages.vipActivatedSuccess'))
    } else if (order.status === 'FAILED') {
      paymentStatus.value = 'failed'
      errorMessage.value = order.remark || t('dashboard.vipCenter.paymentResult.errors.paymentFailed')
    } else {
      // 订单还在处理中，等待一下再检查
      setTimeout(() => {
        checkPaymentResult()
      }, 2000)
    }
    
  } catch (error: any) {
    console.error('检查支付结果失败:', error)
    paymentStatus.value = 'failed'
    errorMessage.value = error.message || t('dashboard.vipCenter.paymentResult.errors.verificationFailed')
  }
}

const fetchOrderDetails = async (orderNo: string) => {
  try {
    const response = await fetch('/api/vip/orders', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    const result = await response.json()
    if (result.success) {
      return result.data
    } else {
      throw new Error(result.message || t('dashboard.vipCenter.paymentResult.errors.fetchOrderFailed'))
    }
  } catch (error) {
    throw error
  }
}

const formatTime = (timeString?: string) => {
  if (!timeString) return ''
  return new Date(timeString).toLocaleString('zh-CN')
}

const goToProfile = () => {
  router.push('/profile')
}

const goToHome = () => {
  router.push('/')
}

const retryPayment = () => {
  // 显示升级对话框重新支付
  vipStore.showUpgradeDialog()
  router.push('/')
}
</script>

<style scoped>
.payment-result-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.result-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  max-width: 500px;
  width: 100%;
}

.result-content {
  padding: 60px 40px;
  text-align: center;
}

.result-icon {
  margin-bottom: 30px;
}

.success-icon {
  font-size: 80px;
  color: #67c23a;
  animation: bounce 1s ease-in-out;
}

.failed-icon {
  font-size: 80px;
  color: #f56c6c;
  animation: shake 0.5s ease-in-out;
}

.cancelled-icon {
  font-size: 80px;
  color: #e6a23c;
}

.loading-icon {
  font-size: 80px;
  color: #409eff;
  animation: spin 1s linear infinite;
}

.result-title {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 15px 0;
  color: #303133;
}

.result-message {
  font-size: 16px;
  color: #606266;
  margin: 0 0 40px 0;
  line-height: 1.5;
}

.success-details {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 40px;
  text-align: left;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #909399;
  font-weight: 500;
}

.value {
  color: #303133;
  font-weight: 600;
}

.amount {
  color: #f39c12;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
}

/* 动画效果 */
@keyframes bounce {
  0%, 20%, 53%, 80%, 100% {
    transform: translate3d(0, 0, 0);
  }
  40%, 43% {
    transform: translate3d(0, -20px, 0);
  }
  70% {
    transform: translate3d(0, -10px, 0);
  }
  90% {
    transform: translate3d(0, -4px, 0);
  }
}

@keyframes shake {
  10%, 90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%, 80% {
    transform: translate3d(2px, 0, 0);
  }
  30%, 50%, 70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%, 60% {
    transform: translate3d(4px, 0, 0);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .result-content {
    padding: 40px 30px;
  }
  
  .result-title {
    font-size: 24px;
  }
  
  .success-icon,
  .failed-icon,
  .cancelled-icon,
  .loading-icon {
    font-size: 60px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>